package com.tiancai.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tiancai.constant.JwtClaimsConstant;
import com.tiancai.context.BaseContext;
import com.tiancai.exception.AccountNotFoundException;
import com.tiancai.exception.UsernameErrorException;
import com.tiancai.pojo.dto.UserDto;
import com.tiancai.pojo.dto.UserLoginDto;
import com.tiancai.pojo.dto.UserRegistDto;
import com.tiancai.pojo.po.Orders;
import com.tiancai.pojo.po.User;
import com.tiancai.pojo.po.UserRole;
import com.tiancai.pojo.po.Work;
import com.tiancai.pojo.vo.UserDetailVo;
import com.tiancai.pojo.vo.UserLoginVo;
import com.tiancai.properties.JwtProperties;
import com.tiancai.result.PageResult;
import com.tiancai.result.Result;
import com.tiancai.service.*;
import com.tiancai.utils.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tiancai
 * @since 2025-03-09
 */
@RestController
@RequestMapping("/users")
@Tag(name = "用户管理")
@Slf4j
@CrossOrigin
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private MailService mailService;

    @Autowired
    private IWorkService workService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IUserRoleService userRoleService;
    @PostMapping("/sendEmail")
    @Operation(summary = "发送邮件")
    public Result sendEmail(String email, HttpSession httpSession){
        mailService.sendMimeMail(email, httpSession);
        return Result.success();
    }
    //使用邮箱注册用户
    @PostMapping("/regist")
    @Operation(summary = "用户注册")
    public Result<UserDetailVo> regist(@RequestBody UserRegistDto userRegistDto, HttpSession session){
        UserDetailVo userDetailVo = new UserDetailVo();
        User user = mailService.registered(userRegistDto, session);
        BeanUtils.copyProperties(user, userDetailVo);
        return Result.success(userDetailVo);
    }


    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<UserLoginVo> login(@RequestBody UserLoginDto userLoginDto) {
        // 打印当前时间，格式为 yyyy-MM-dd HH:mm:ss
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("当前时间：{}", sdf.format(new Date()));
        log.info("用户登录：{}", userLoginDto.getEmail());

            User user = userService.login(userLoginDto.getEmail(), userLoginDto.getPassword());

            // 登录成功后，生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.USER_ID, user.getId());
            String token = JwtUtil.createJWT(
                    jwtProperties.getAdminSecretKey(),
                    jwtProperties.getAdminTtl(),
                    claims);
            //根据用户id查询用户的所有角色的String数组
            List<String> roles = userRoleService.getRolesByUserId(user.getId());


            // List<UserRole> userRoleList = userRoleService.list(new QueryWrapper<UserRole>().lambda().eq(UserRole::getUserId, user.getId()));
            UserLoginVo userLoginVo = UserLoginVo.builder()
                    .userId(user.getId())
                    .username(user.getUsername())
                    .email(user.getEmail())
                    .code(user.getCode())
                    .roles(roles)
                    .token(token)
                    .build();

            return Result.success(userLoginVo);
    }



    // @GetMapping("/sortBy")
    // @Operation(summary = "通过拥有作品数、上传作品数、交易数、被收藏数中文任意一项进行排序")
    // @Parameters({
    //         @Parameter(name = "sortBy", description = "排序字段，可选值为 ownCount、uploadCount、tradeCount、ownCollectCount"),
    //         @Parameter(name = "page", description = "页码"),
    //         @Parameter(name = "pageSize", description = "每页记录数")
    // })
    // public Result<Page<UserDetailVo>> sortBy(@RequestParam(value = "sortBy", required = false) String sortBy,
    //                                          @RequestParam(value = "currPage") Integer page,
    //                                          @RequestParam(value = "pageSize") Integer pageSize) {
    //     QueryWrapper<User> wrapper = new QueryWrapper<>();
    //
    //     // 判断 sortBy 参数并应用相应的排序
    //     if (StringUtils.isNotBlank(sortBy)) {
    //         switch (sortBy) {
    //             case "ownCount":
    //                 wrapper.lambda().orderByDesc(User::getOwnCount);  // 按拥有作品数排序
    //                 break;
    //             case "uploadCount":
    //                 wrapper.lambda().orderByDesc(User::getUploadCount);  // 按上传作品数排序
    //                 break;
    //             case "tradeCount":
    //                 wrapper.lambda().orderByDesc(User::getTradeCount);  // 按交易数排序
    //                 break;
    //             default:
    //                 // 如果传入的排序字段无效，可以选择按默认排序方式处理
    //                 wrapper.lambda().orderByDesc(User::getOwnCollectCount);  // 按被收藏数排序
    //                 break;
    //         }
    //     }
    //
    //     // 执行查询并返回结果
    //     Page<User> pageInfo = userService.page(new Page<>(page, pageSize), wrapper);
    //
    //     // 将 User 对象转换为 UserDetailVo 对象
    //     List<UserDetailVo> userDetailVos = pageInfo.getRecords().stream()
    //             .map(user -> {
    //                 UserDetailVo userDetailVo = new UserDetailVo();
    //                 BeanUtils.copyProperties(user, userDetailVo); // 复制非密码字段
    //                 return userDetailVo;
    //             })
    //             .collect(Collectors.toList());
    //
    //     // 返回分页结果
    //     Page<UserDetailVo> resultPage = new Page<>(pageInfo.getCurrent(), pageInfo.getSize(), pageInfo.getTotal());
    //     resultPage.setRecords(userDetailVos);
    //     return Result.success(resultPage);
    // }

    @GetMapping()
    @Operation(summary = "根据id查询用户")
    public Result<UserDetailVo> getUserById() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getId, BaseContext.getCurrentId());
        UserDetailVo userDetailVo = new UserDetailVo();
        BeanUtils.copyProperties(userService.getOne(wrapper), userDetailVo);
        return Result.success(userDetailVo);
    }

    //更新用户信息
    @PutMapping()
    @Operation(summary = "更新用户信息")
    @Parameters({
            @Parameter(name = "phone", description = "手机号"),
            @Parameter(name = "avatar", description = "头像"),
            @Parameter(name = "username", description = "用户名"),
            @Parameter(name = "remark", description = "备注")
    })
    public Result<User> updateUser(@RequestBody UserDto userDto){
        userService.updateUser(userDto);
        return Result.success();
    }


    @GetMapping("/getWorkByUserId")
    @Operation(summary = "根据用户id查询该用户所有作品")
    public Result<List<Work>> getWorkByUserId(@RequestParam Long userId){
        QueryWrapper<Work> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Work::getUserId,userId);
        return Result.success(workService.list(wrapper));
    }

    //根据用户名查询所有订单
    @GetMapping("/getOrderByUserId")
    @Operation(summary = "根据用户id查询该用户所有订单")
    public Result<List<Orders>> getOrderByUserId(@RequestParam Long userId){
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Orders::getCustomerId,userId);
        return Result.success(orderService.list(wrapper));
    }

    //查询用户列表接口，需要通过交易作品数排序、通过手机号、用户名查询，并返回用户的roles字段，用来回显和修改角色。
    // @GetMapping("/list")
    // @Operation(summary = "查询用户列表")
    // public Result<Page<UserDetailVo>> list(@RequestParam(value = "phone", required = false) String phone,
    //                                        @RequestParam(value = "username", required = false) String username,
    //                                        @RequestParam(value = "sortBy", required = false) String sortBy,
    //                                        @RequestParam(value = "currPage", defaultValue = "1") Integer page,
    //                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
    //     QueryWrapper<User> wrapper = new QueryWrapper<>();
    //     // phone不为空根据phone查找，username不为空根据username查找，默认是tradeCount
    //     if (StringUtils.isNotBlank(phone))
    //         wrapper.lambda().eq(User::getPhone, phone);
    //     if (StringUtils.isNotBlank(username))
    //         wrapper.lambda().eq(User::getUsername, username);
    //     if (sortBy != null && sortBy.equals("tradeCount"))
    //         wrapper.lambda().orderByDesc(User::getTradeCount);
    //
    //     // 分页查询
    //     Page<User> userPage = new Page<>(page, pageSize);
    //     Page<User> userList = userService.page(userPage, wrapper);
    //
    //     // 查询角色表，给每个用户加上角色列表并返回
    //     List<UserDetailVo> userDetailVoList = new ArrayList<>();
    //     for (User user : userList.getRecords()) {
    //         List<String> roles = userRoleService.getRolesByUserId(user.getId());
    //         // 新建用户详细对象
    //         UserDetailVo userDetailVo = new UserDetailVo();
    //         BeanUtils.copyProperties(user, userDetailVo);
    //         userDetailVo.setRoles(roles);
    //         userDetailVoList.add(userDetailVo);
    //     }
    //
    //     // 封装分页结果
    //     Page<UserDetailVo> pageInfo = new Page<>(page, pageSize);
    //     pageInfo.setRecords(userDetailVoList);
    //     pageInfo.setTotal(userList.getTotal());
    //
    //     return Result.success(pageInfo);
    // }
    //
    //
    @GetMapping("/list")
    @Operation(summary = "查询用户列表")
    @Parameters({
            @Parameter(name = "phone", description = "手机号"),
            @Parameter(name = "username", description = "用户名"),
            @Parameter(name = "sortBy", description = "排序字段，可选值为 ownCount、uploadCount、tradeCount、ownCollectCount"),
            @Parameter(name = "currPage", description = "页码"),
            @Parameter(name = "pageSize", description = "每页记录数")
    })
    public Result<Page<UserDetailVo>> list(
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "sortBy", required = false) String sortBy,
            @RequestParam(value = "currPage", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {

        QueryWrapper<User> wrapper = new QueryWrapper<>();

        // 根据手机号和用户名进行查询
        if (StringUtils.isNotBlank(phone)) {
            wrapper.lambda().eq(User::getPhone, phone);
        }
        if (StringUtils.isNotBlank(username)) {
            wrapper.lambda().eq(User::getUsername, username);
        }

        // 根据排序字段进行排序
        if (StringUtils.isNotBlank(sortBy)) {
            switch (sortBy) {
                case "ownCount":
                    wrapper.lambda().orderByDesc(User::getOwnCount);  // 按拥有作品数排序
                    break;
                case "uploadCount":
                    wrapper.lambda().orderByDesc(User::getUploadCount);  // 按上传作品数排序
                    break;
                case "ownCollectCount":
                    wrapper.lambda().orderByDesc(User::getOwnCollectCount);  // 按被收藏数排序
                    break;
                default:
                    // 默认按交易数排序
                    wrapper.lambda().orderByDesc(User::getTradeCount);
                    break;
            }
        }

        // 分页查询
        Page<User> userPage = new Page<>(page, pageSize);
        Page<User> userList = userService.page(userPage, wrapper);

        // 查询角色表，给每个用户加上角色列表并返回
        List<UserDetailVo> userDetailVoList = new ArrayList<>();
        for (User user : userList.getRecords()) {
            List<String> roles = userRoleService.getRolesByUserId(user.getId());
            UserDetailVo userDetailVo = new UserDetailVo();
            BeanUtils.copyProperties(user, userDetailVo);
            userDetailVo.setRoles(roles);
            userDetailVoList.add(userDetailVo);
        }

        // 封装分页结果
        Page<UserDetailVo> pageInfo = new Page<>(page, pageSize);
        pageInfo.setRecords(userDetailVoList);
        pageInfo.setTotal(userList.getTotal());

        return Result.success(pageInfo);
    }


    //管理员修改用户权限
    @PostMapping("/updateRole/{userId}")
    @Operation(summary = "管理员修改用户权限为管理员")
    public Result updateRole(@PathVariable Long userId){
        //查询当前用户的角色列表中是否有admin角色，如果有，则不能修改，否则可以修改
        if (userRoleService.getRolesByUserId(BaseContext.getCurrentId()).contains("admin")){
            UserRole userRole = UserRole.builder()
                    .userId(userId)
                    .role("admin")
                    .build();
            userRoleService.save(userRole);
        }else {
            return Result.error("不是管理员，回家吧孩子");
        }
        return Result.success();
    }
    //修改用户权限，废除他的管理员身份
    @PostMapping("/deleteRole/{userId}")
    @Operation(summary = "管理员修改用户权限为普通用户")
    public Result deleteRole(@PathVariable Long userId){
        //查询当前用户的角色列表中是否有admin角色，如果有，则不能修改，否则可以修改
        if (userRoleService.getRolesByUserId(BaseContext.getCurrentId()).contains("admin")){
            userRoleService.remove(new QueryWrapper<UserRole>().lambda().eq(UserRole::getUserId,userId));
        }else {
            return Result.error("不是管理员，回家吧孩子");
        }
        return Result.success();
    }
    //根据用户id查看用户详细信息
    @GetMapping("/getUserById")
    @Operation(summary = "根据id查询用户详细信息")
    public Result<UserDetailVo> getUserById(@RequestParam Long id){
        User user = userService.getById(id);
        List<String> roles = userRoleService.getRolesByUserId(id);
        UserDetailVo userDetailVo = new UserDetailVo();
        BeanUtils.copyProperties(user,userDetailVo);
        userDetailVo.setRoles(roles);
        return Result.success(userDetailVo);
    }

    //访问量加一
    @GetMapping("/addViewCount/{id}")
    @Operation(summary = "访问量加一")
    public Result addViewCount(@PathVariable Long id){
        User user = userService.getById(id);
        Long ownVisitCount = user.getOwnVisitCount();
        if (ownVisitCount == null) {
            ownVisitCount = 1L;  // 设置默认值
            user.setOwnVisitCount(ownVisitCount);
        }else {
            user.setOwnVisitCount(user.getOwnVisitCount()+1);
        }
        userService.updateById(user);
        return Result.success();
    }
}
